package com.cci.kangdao.service.impl;

import com.cci.kangdao.dao.EngineMsgDao;
import com.cci.kangdao.dao.ServiceStationDao;
import com.cci.kangdao.dao.model.*;
import com.cci.kangdao.redis.RedisClientUtils;
import com.cci.kangdao.service.PropertiesUtils;
import com.cci.kangdao.service.ServiceStationServ;
import com.cci.kangdao.utilTool.*;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Service("ssService")
public class ServiceStationServImpl implements ServiceStationServ {

	private static final Logger log = Logger.getLogger(ServiceStationServImpl.class);
	
	@Autowired
	private PropertiesUtils propertiesUtils;
	@Autowired
	private RedisClientUtils redisClientUtils;
	@Autowired
	private ServiceStationDao serviceStationDao;
	@Autowired
	private EngineMsgDao engineMsgDao;
	
	@Override
	public ModelAndView getBaseInfo(Map<String, Object> map) {
		try{
			HttpServletRequest request = (HttpServletRequest)map.get("request");
			HttpServletResponse response = (HttpServletResponse)map.get("response");
			JSONObject obj = new JSONObject();			
			/**
			 * 1、首先看看redis是否存在字典项，不存在则查询数据库
			 */			
			List<DictionariesT> dictionariesList = (List<DictionariesT>)redisClientUtils.getObject("dictionariesList");
			if(dictionariesList == null || dictionariesList.size()==0){	
				//放入redis中
				dictionariesList = serviceStationDao.findDictionariesList(null);
				int redisCacheTime = Integer.valueOf(propertiesUtils.getPropertiesValue("redisCacheTime"));
				redisClientUtils.setObject("dictionariesList", dictionariesList, redisCacheTime);
			}
			
			/**
			 * 2、将字典项内容返回给用户
			 */
			String dictionLabel = "";
			JSONObject content;	
			JSONArray jsonArray = null;
			for(DictionariesT  bean : dictionariesList){
				if(bean.getDtableName().trim().equals(dictionLabel)){					
					content = new JSONObject();	
					content.put("DInt", bean.getDInt());
					content.put("DValue", bean.getDvalue());
					jsonArray.put(content);
				}else{
					//如果字典项标签不等空则将数据放入到json
					if(!dictionLabel.trim().equals("")){
						obj.put(dictionLabel, jsonArray);
					}

					dictionLabel = bean.getDtableName();
					jsonArray = new JSONArray();
					content = new JSONObject();
					content.put("DInt", bean.getDInt());
					content.put("DValue", bean.getDvalue());
					jsonArray.put(content);
				}				
			}
			obj.put(dictionLabel, jsonArray);
			
			//车辆企业返回给用户（OEM/SSOEM）
			List<Map<String, Object>> comList = serviceStationDao.getSSHasCompany();
			
			if(null != comList && comList.size() > 0) {
				obj.put("companyList", comList);
			} else {
				obj.put("companyList", new ArrayList<Map<String, Object>>());
			}
			
			obj.put("status", 0);
			obj.put("msg", "");
			
			//返回客户
			ParameterTool.writeResponse(response, obj.toString());	
		}catch(Exception ex) {
			log.error(ex.getMessage(), ex);
		}
		return null;
	}

	@Override
	public ModelAndView getEngsByCom(Map<String, Object> map) {
		try{
			HttpServletRequest request = (HttpServletRequest)map.get("request");
			HttpServletResponse response = (HttpServletResponse)map.get("response");
			JSONObject obj = new JSONObject();	
			
			/**
			 * 1、必填项字段
			 */
			if(map.get("companyId") == null  || map.get("companyId").toString().equals("")){
				obj.put("status", -5);
				obj.put("msg", ApiErrorCode.getInstance().getErrorMsg(-5));
				
				//返回客户
				ParameterTool.writeResponse(response, obj.toString());	
				obj = null;
				return null;
			}
			
			/**
			 * 1、首先看看redis是否存在字典项，不存在则查询数据库
			 */			
			List<EngineTypeT> engineTypeList = serviceStationDao.findEngineTypeList(map.get("companyId").toString());
			
			JSONArray jsonArray = new JSONArray();
			for(EngineTypeT bean : engineTypeList){
				JSONObject content = new JSONObject();
				content.put("DInt", ""+bean.getId());
				content.put("DValue", bean.getTypename());
				jsonArray.put(content);
			}
			obj.put("EngineType", jsonArray);
			obj.put("status", 0);
			obj.put("msg", "");
			
			//返回客户
			ParameterTool.writeResponse(response, obj.toString());	
		}catch(Exception ex) {
			log.error(ex.getMessage(), ex);
		}
		return null;
	}

	@Override
	public ModelAndView getStations(Map<String, Object> map) {
		try{
			HttpServletRequest request = (HttpServletRequest)map.get("request");
			HttpServletResponse response = (HttpServletResponse)map.get("response");
			JSONObject obj = new JSONObject();		
							
			/**
			 * 1、必填项字段
			 */
			if(map.get("position") == null  || map.get("position").toString().equals("")){
				obj.put("status", -5);
				obj.put("msg", ApiErrorCode.getInstance().getErrorMsg(-5));
				
				//返回客户
				ParameterTool.writeResponse(response, obj.toString());	
				obj = null;
				return null;
			}
			
			if(map.get("serviceType") == null  || map.get("serviceType").toString().equals("")){
				obj.put("status", -5);
				obj.put("msg", ApiErrorCode.getInstance().getErrorMsg(-5));
				
				//返回客户
				ParameterTool.writeResponse(response, obj.toString());	
				obj = null;
				return null;
			}
			
//			if(map.get("vehicleType") == null  || map.get("vehicleType").toString().equals("")){
//				obj.put("status", -5);
//				obj.put("msg", ApiErrorCode.getInstance().getErrorMsg(-5));
//				
//				//返回客户
//				ParameterTool.writeResponse(response, obj.toString());	
//				obj = null;
//				return null;
//			}
			
			if(map.get("enginType") == null  || map.get("enginType").toString().equals("")){
				obj.put("status", -5);
				obj.put("msg", ApiErrorCode.getInstance().getErrorMsg(-5));
				
				//返回客户
				ParameterTool.writeResponse(response, obj.toString());	
				obj = null;
				return null;
			}
			String position = ""+map.get("position");
			position = AESTool.decryptString(position); //解密			
			int index = position.indexOf(",");
			map.put("lat", position.substring(0, index));
			map.put("lon", position.substring(index+1));
			
			if(map.get("searchTxt") != null && !map.get("searchTxt").toString().equals("")){
				map.put("searchTxt", "%"+map.get("searchTxt")+"%");
			}
			
			if(map.get("serviceType") != null && !map.get("serviceType").toString().equals("")){
				String serviceType = ""+map.get("serviceType");
				if(serviceType.endsWith(",")){
					serviceType =  serviceType.substring(0, serviceType.length()-1);
				}
//				if(serviceType.contains(",")){
//					serviceType = " in ("+serviceType+")";
//				}else{
//					serviceType = " ="+serviceType;
//				}
				String[] split = serviceType.split(",");
				ArrayList<String> arrayList = new ArrayList<String>(split.length);
				Collections.addAll(arrayList, split);
				map.put("serviceType", arrayList);
			}
			
			if(map.get("vehicleType") != null && !map.get("vehicleType").toString().equals("")){
				String vehicleType = ""+map.get("vehicleType");
//				if(vehicleType.endsWith(",")){
//					vehicleType =  vehicleType.substring(0, vehicleType.length()-1);
//				}
//				if(vehicleType.contains(",")){
//					vehicleType = " in ("+vehicleType+")";
//				}else{
//					vehicleType = " ="+vehicleType;
//				}

				String[] split = vehicleType.split(",");
				ArrayList<String> arrayList = new ArrayList<String>(split.length);
				Collections.addAll(arrayList, split);
				map.put("vehicleType", arrayList);
			}
			
			if(map.get("SSLevel") != null && !map.get("SSLevel").toString().equals("")){
				String SSLevel = ""+map.get("SSLevel");
				if(SSLevel.endsWith(",")){
					SSLevel =  SSLevel.substring(0, SSLevel.length()-1);
				}
//				if(SSLevel.contains(",")){
//					SSLevel = " in ("+SSLevel+")";
//				}else{
//					SSLevel = " ="+SSLevel;
//				}
				String[] split = SSLevel.split(",");
				ArrayList<String> arrayList = new ArrayList<String>(split.length);
				Collections.addAll(arrayList, split);
				map.put("SSLevel", arrayList);
			}
			
			if(map.get("SSType") != null && !map.get("SSType").toString().equals("")){
				String SSType = ""+map.get("SSType");
				if(SSType.endsWith(",")){
					SSType =  SSType.substring(0, SSType.length()-1);
				}
//				if(SSType.contains(",")){
//					SSType = " in ("+SSType+")";
//				}else{
//					SSType = " ="+SSType;
//				}
				String[] split = SSType.split(",");
				ArrayList<String> arrayList = new ArrayList<String>(split.length);
				Collections.addAll(arrayList, split);
				map.put("SSType", arrayList);
			}
			
			if(map.get("enginType") != null && !map.get("enginType").toString().equals("")){
				String enginType = map.get("enginType").toString();
				String[] split = enginType.split(",");
				ArrayList<String> arrayList = new ArrayList<String>(split.length);
				Collections.addAll(arrayList, split);
				map.put("enginType", arrayList);
			}
			
			/**
			 * 2、查询所有服务站信息
			 */		
			int page = MapUtils.getInteger(map,"page",1);
			int pagesize = Integer.valueOf(this.propertiesUtils.getPropertiesValue("pagesize"));
			/**
			 * 使用pagehelper分页报错
			 */
			//PageHelper.startPage(page, pagesize);
			map.put("page", (page-1)*pagesize);
			map.put("pagesize", pagesize);
			List<ServiceStationT> list = serviceStationDao.getStations(map);
			
			/**
			 * 从redis中获取字典项的信息
			 * 如果redis中不存在，则重新放入
			 */
			Map<String, String> dictionariesMap = (Map<String, String>)redisClientUtils.getObject("dictionariesMap");
			if(dictionariesMap == null){
				int redisCacheTime = Integer.valueOf(propertiesUtils.getPropertiesValue("redisCacheTime"));
				List<DictionariesT> dictionariesList = (List<DictionariesT>)redisClientUtils.getObject("dictionariesList");
				if(dictionariesList == null){
					//放入redis中
					dictionariesList = serviceStationDao.findDictionariesList(null);					
					redisClientUtils.setObject("dictionariesList", dictionariesList, redisCacheTime);
				}
				dictionariesMap = new HashMap<String, String>();
				for(DictionariesT bean : dictionariesList){
					dictionariesMap.put(bean.getDtableName()+bean.getDInt(), bean.getDvalue());
				}
				//放入redis中
				redisClientUtils.setObject("dictionariesMap", dictionariesMap, redisCacheTime);
			}
			
			/**
			 * 遍历服务站信息放入到用户中
			 */
			JSONArray ServiceStationJsonArray = new JSONArray();
			JSONObject content;	
			JSONArray jsonArray = null;
			List<SSRepairT> SSRepairList = null;
			List<EngineTypeT> engineTypeList = null;
			for(ServiceStationT ssBean : list){
				content =  new JSONObject();
				
				content.put("id", AESTool.encryptString(ssBean.getId().toString()));
				content.put("stationName", ssBean.getStationname());
				content.put("province", ssBean.getProvince());
				content.put("city", ssBean.getCity());
				content.put("area", ssBean.getArea());
				content.put("address", ssBean.getAddress());
				content.put("distance", ssBean.getDistance());
				content.put("telephone", ssBean.getTelephone());
				content.put("phone", ssBean.getPhone());
				content.put("position", ssBean.getPositionLat()+","+ssBean.getPositionLon());
				content.put("remark", ssBean.getRemark());
				
				/**
				 * 获取服务站的级别SSLevel
				 * 根据服务站id查询服务站维修机型
				 * 根据服务站Id查询服务站图片
				 */
				//获取服务站的级别SSLevel
				SSRepairList = serviceStationDao.findSSRepair(ssBean.getId().toString());
				jsonArray = new JSONArray();
				JSONArray jsonArray1 = new JSONArray();//服务站类型
				for(SSRepairT ssRepairT : SSRepairList){
					String SSLevel = dictionariesMap.get("SSLevel"+ssRepairT.getSslevel());
					//去除null和去重
					if( SSLevel!= null && !jsonArray.toString().contains(SSLevel) ){
						jsonArray.put(SSLevel);
					}	
					String SSType = dictionariesMap.get("SSType"+ssRepairT.getSstype());
					//去除null和去重
					if( SSType!= null && !jsonArray1.toString().contains(SSType) ){
						jsonArray1.put(SSType);
					}
				}
				content.put("SSLevel", jsonArray);
				content.put("SSType", jsonArray1);
				SSRepairList.clear();
				SSRepairList = null;
				
				//根据服务站id查询服务站维修机型
				engineTypeList = serviceStationDao.findEngineType(ssBean.getId().toString());
				String engineTypeString = "";
				for(EngineTypeT engineTypeT : engineTypeList){
					engineTypeString += engineTypeT.getTypename()+"、";
				}
				if(engineTypeString.endsWith("、")){
					engineTypeString =  engineTypeString.substring(0, engineTypeString.length()-1);
				}
				content.put("enginType", engineTypeString);
				engineTypeList.clear();
				engineTypeList = null;
				
				//根据服务站Id查询服务站图片 
				int redisCacheTime = Integer.valueOf(propertiesUtils.getPropertiesValue("redisCacheTime"));
				List<ServiceStationImgT> serviceStationImgList = (List<ServiceStationImgT>)redisClientUtils.getObject("serviceStationImg"+ssBean.getId());
				if(serviceStationImgList == null){
					serviceStationImgList = serviceStationDao.findServiceStationImg(ssBean.getId().toString());
					//放入redis中			
					redisClientUtils.setObject("serviceStationImg"+ssBean.getId(), serviceStationImgList, redisCacheTime);
				}
				jsonArray = new JSONArray();
				for(ServiceStationImgT serviceStationImgT : serviceStationImgList){
					jsonArray.put(serviceStationImgT.getImgurl());
				}
				content.put("img", jsonArray);
				serviceStationImgList.clear();
				serviceStationImgList = null;

				ServiceStationJsonArray.put(content);
			}		
			
			obj.put("status", 0);
			obj.put("msg", "");
			obj.put("serviceStations", ServiceStationJsonArray);
			//返回客户
			ParameterTool.writeResponse(response, obj.toString());	
			obj = null;
		}catch(Exception ex) {
			log.error(ex.getMessage(), ex);
		}
		return null;
	}

	@Override
	public ModelAndView getMetadataForServiceStation(Map<String, Object> map) {
		try{
			HttpServletResponse response = (HttpServletResponse)map.get("response");
			JSONObject obj = new JSONObject();		
			Map<String, Object> data = (Map<String, Object>)redisClientUtils.getObject("metadataForServiceStation");
			if(null == data){	
				data = new HashMap<>();
				//1. 获取排放标准
				List<Map<String, Object>> ssAuth = serviceStationDao.getSSAuth();
				data.put("ssAuth", ssAuth);
				//2. 获取车辆应用
				List<Map<String, Object>> EngineType = serviceStationDao.getEngineType();
				data.put("EngineType", EngineType);
				//3. 获取发动机机型
				List<Map<String, Object>> VehicleType = serviceStationDao.getVehicleType();
				data.put("VehicleType", VehicleType);
				//4. 获取车辆厂家
				List<Map<String, Object>> OEM = serviceStationDao.getOEM();
				data.put("OEM", OEM);
				int redisCacheTime = Integer.valueOf(propertiesUtils.getPropertiesValue("redisCacheTime"));
				redisClientUtils.setObject("metadataForServiceStation", data, redisCacheTime);
			}
			
			obj.put("status", 0);
			obj.put("msg", "");
			obj.put("data",data);
			//返回客户
			ParameterTool.writeResponse(response, obj.toString());	
		}catch(Exception ex) {
			log.error(ex.getMessage(), ex);
		}
		return null;
	}

	@Override
	public ModelAndView getServiceStationV2(Map<String, Object> map) throws JSONException {
		HttpServletResponse response = (HttpServletResponse)map.get("response");
		HttpServletRequest request = (HttpServletRequest)map.get("request");
		Map<String, Object> data = new HashMap<>();
		//验证必传项是否有值
		if(StringUtils.isBlank(MapUtils.getString(map, "positionLon")) || StringUtils.isBlank(MapUtils.getString(map, "positionLat")) || StringUtils.isBlank(MapUtils.getString(map, "isCustomer")) || StringUtils.isBlank(MapUtils.getString(map, "page")) || StringUtils.isBlank(MapUtils.getString(map, "pageSize"))) {
			ParameterTool.writeErrorResponse(response, -5);
			return null;
		}
		Long userId = MapUtils.getLong(map, "userId");
		String userid = request.getHeader("userid");
		userid = AESTool.decryptString(userid);//解密userid
		if(null != userId && !String.valueOf(userId).equals(userid)){
			ParameterTool.writeResponse(response, -2, "非法操作");
			return null;
		}
		int page = MapUtils.getInteger(map,"page",1);
		int pageSize = MapUtils.getInteger(map,"pageSize",20);
		
		map.put("page", (page-1)*pageSize);
		map.put("pageSize", pageSize);
		
		int isCustomer = MapUtils.getIntValue(map, "isCustomer");
		String search = MapUtils.getString(map, "search", null);
		String authType = MapUtils.getString(map, "authType", null);
		String vehicleType = MapUtils.getString(map, "vehicleType", null);
		String engineType = MapUtils.getString(map, "engineType", null);
		String oem = MapUtils.getString(map, "oem", null);
		
		Set<String> smns = new HashSet<>();
		List<Map<String, Object>> engines = new ArrayList<>();
		
		boolean checkWithEngine = false;
		
		if(isCustomer == 1) {
			//验证用户是否绑定设备，如果没有设备绑定，则提示用户
			engines = serviceStationDao.getEngineList(userId);
			//判断用户是否选择了筛选条件或者输入了搜索内容。如果是，则不判断用户的设备；如果否，则根据用户绑定设备筛选
			if(StringUtils.isBlank(search) && StringUtils.isBlank(authType) && StringUtils.isBlank(vehicleType) && StringUtils.isBlank(engineType) && StringUtils.isBlank(oem)) {
				
				if(CollectionUtils.isEmpty(engines)) {
					ParameterTool.writeResponse(response, 2, "您还未添加任何设备，请添加设备！");
					return null;
				}
				data.put("engines", engines);
				//如果是普通用户，需要获取用户关联的设备
				String esn = MapUtils.getString(map, "ESN", "");
				if(StringUtils.isBlank(esn)) {
					//获取用户关联设备的全部SMN
					List<String> smnList = serviceStationDao.getSMNByUser(userId);
					if(CollectionUtils.isEmpty(smnList)) {
						ParameterTool.writeResponse(response, 1, "您绑定的设备，暂未检索到服务站，请通过搜索功能检索服务站，谢谢！", data);
						return null;
					}
					smns.addAll(smnList);
				} else {
					//获取用户选定设备的SMN
					EngineMsg engine = engineMsgDao.getEngineMsgByESNString(esn);
					if(null == engine) {
						ParameterTool.writeResponse(response, 1, "您绑定的设备，暂未检索到服务站，请通过搜索功能检索服务站，谢谢！", data);
						return null;
					}
					smns.add(engine.getSMN());
				}
				
				//验证用户绑定设备是否有服务站
				int count = serviceStationDao.getServiceStationCountForCustomer(smns);
				
				if(count == 0) {
					ParameterTool.writeResponse(response, 1, "您绑定的设备，暂未检索到服务站，请通过搜索功能检索服务站，谢谢！", data);
					return null;
				}
				map.put("smns", smns);
				checkWithEngine = true;
			} else {
				data.put("engines", engines);
			}
			
		}
		
		//验证搜索条件是ESN还是服务站名称
		if(StringUtils.isNotBlank(search)) {
			if(search.trim().matches("\\d{8}")) {
				EngineMsg engine = engineMsgDao.getEngineMsgByESNString(search.trim());
				if(null != engine) {
					map.put("SMNEqual", StringUtils.isNotBlank(engine.getSMN())? engine.getSMN(): "");
				}
				
			} else {
				map.put("stationNameLike", search.trim());
			}
		}
		
		if(StringUtils.isNotBlank(authType)) {
			String[] ats = authType.split(",");
			map.put("ats", ats);
		}
		
		if(StringUtils.isNotBlank(oem)) {
			String[] oems = oem.split(",");
			map.put("oems", oems);
		}
        //2.8.0需求   过滤不显示服务类别 =（HMLD保养级、区域服务站、HMLD零件、DPF、HHP修理级、HHP零件、HHP零件贸易商、发电机组）。
        List<String> filterList = Arrays.asList("HMLD保养级", "区域服务站", "HMLD零件", "DPF", "HHP修理级", "HHP零件", "HHP零件贸易商", "发电机组服务", "燃油服务", "后处理服务");
		//获取dbu渠道下授权服务站id和授权级别   2.8.0需求使用
		List<Map<String, Object>> dbuSsrepairList = serviceStationDao.getDBUSsrepairList(1);
		List<Long> stationIdList = new ArrayList<>();
		if (CollectionUtils.isNotEmpty(dbuSsrepairList)) {
			for (Map<String, Object> dbuSsrepair : dbuSsrepairList) {
				boolean authorizationLeve = false;
				Long servieStationId = MapUtils.getLongValue(dbuSsrepair, "ServiceStationID", 0);
				String authorizationLevelMsg = MapUtils.getString(dbuSsrepair, "AuthorizationLevel", "");
				if (StringUtils.isNotEmpty(authorizationLevelMsg)) {
					List<String> authorizationLevelList = Arrays.asList(authorizationLevelMsg.split(";"));
					for (String authorizationLevel : authorizationLevelList) {
						authorizationLeve = !filterList.contains(authorizationLevel);
						if (authorizationLeve) {
							break;
						}
					}
					if (!authorizationLeve) {
						stationIdList.add(servieStationId);
					}
				}
			}
		}
		map.put("stationIdList", stationIdList);
        List<String> engineTypeList = StringToool.getStringList(MapUtils.getString(map, "engineType"), ",");
        if (CollectionUtils.isNotEmpty(engineTypeList)) {
			map.put("engineType", engineTypeList);
		} else {
			map.remove("engineType");
		}
        List<String> vehicleTypeList = StringToool.getStringList(MapUtils.getString(map, "vehicleType"), ",");
		if (CollectionUtils.isNotEmpty(vehicleTypeList)) {
			map.put("vehicleType", vehicleTypeList);
		} else {
			map.remove("vehicleType");
		}

        List<ServiceStationT> stations = new ArrayList<>();
        if (checkWithEngine) {
			stations = serviceStationDao.getServiceStationForCustomer(map);
        } else {
			stations = serviceStationDao.getServiceStationForNonCustomer(map);
        }

        JSONArray stationArray = getStationInfo(stations);

        data.put("stations", stationArray);

		JSONObject obj = new JSONObject();
		obj.put("status", 0);
		obj.put("msg", "");
		obj.put("data",data);
		//返回客户
		ParameterTool.writeResponse(response, obj.toString());
		
		return null;
	}

	@Override
	public ModelAndView getOutServiceStation(Map<String, Object> map) {
		HttpServletResponse response = (HttpServletResponse)map.get("response");

		Map<String, Object> data = new HashMap<>();
		//验证必传项是否有值
		if(StringUtils.isBlank(MapUtils.getString(map, "positionLon")) || StringUtils.isBlank(MapUtils.getString(map, "positionLat")) || StringUtils.isBlank(MapUtils.getString(map, "page")) || StringUtils.isBlank(MapUtils.getString(map, "pageSize"))) {
			ParameterTool.writeErrorResponse(response, -5);
			return null;
		}

		int page = MapUtils.getInteger(map,"page",1);
		int pageSize = MapUtils.getInteger(map,"pageSize",20);

		map.put("page", (page-1)*pageSize);
		map.put("pageSize", pageSize);

		String search = MapUtils.getString(map, "search", null);
		//验证搜索条件是ESN还是服务站名称
		if (StringUtils.isNotBlank(search)) {
			map.put("stationNameLike", search.trim());
		}
		//2.8.0需求   过滤不显示服务类别 =（HMLD保养级、区域服务站、HMLD零件、DPF、HHP修理级、HHP零件、HHP零件贸易商、发电机组）。
		List<String> filterList = Arrays.asList("HMLD保养级", "区域服务站", "HMLD零件", "DPF", "HHP修理级", "HHP零件", "HHP零件贸易商", "发电机组服务", "燃油服务", "后处理服务");
		//获取dbu渠道下授权服务站id和授权级别   2.8.0需求使用
		List<Map<String, Object>> dbuSsrepairList = serviceStationDao.getDBUSsrepairList(1);
		List<Long> stationIdList = new ArrayList<>();
		if (CollectionUtils.isNotEmpty(dbuSsrepairList)) {
			for (Map<String, Object> dbuSsrepair : dbuSsrepairList) {
				boolean authorizationLeve = false;
				Long servieStationId = MapUtils.getLongValue(dbuSsrepair, "ServiceStationID", 0);
				String authorizationLevelMsg = MapUtils.getString(dbuSsrepair, "AuthorizationLevel", "");
				if (StringUtils.isNotEmpty(authorizationLevelMsg)) {
					List<String> authorizationLevelList = Arrays.asList(authorizationLevelMsg.split(";"));
					for (String authorizationLevel : authorizationLevelList) {
						authorizationLeve = !filterList.contains(authorizationLevel);
						if (authorizationLeve) {
							break;
						}
					}
					if (!authorizationLeve) {
						stationIdList.add(servieStationId);
					}
				}
			}
		}
		map.put("stationIdList", stationIdList);
		map.put("tenFlag",true);
		Long outServiceStationTotal = serviceStationDao.getOutServiceStationTotal(map);
		List<ServiceStationT> stations = serviceStationDao.getOutServiceStation(map);
		data.put("distanceFlag",true);
		if (CollectionUtils.isEmpty(stations)) {
			data.put("distanceFlag",false);
			map.put("pageSize", 5);
			map.remove("tenFlag");
			stations = serviceStationDao.getOutServiceStation(map);
			if(CollectionUtils.isNotEmpty(stations) && StringUtils.isNotBlank(search)){
				stations = stations.stream().filter(e -> e.getStationname().indexOf(search) != -1).collect(Collectors.toList());
			}
			outServiceStationTotal = Long.valueOf(CollectionUtils.isNotEmpty(stations)?stations.size():0);
		}
		JSONArray stationArray = getStationInfo(stations);
		List<Map> maps = JsonUtils.convertJsonArrayToList(stationArray, Map.class);
		for (Map mapvo : maps) {
			mapvo.remove("SSType");
			mapvo.remove("SSLevel");
			mapvo.remove("city");
			mapvo.remove("remark");
			mapvo.remove("position");
			mapvo.remove("img");
			mapvo.remove("province");
			mapvo.remove("concact");
			if (StringUtils.isNotBlank(MapUtils.getString(mapvo,"enginType"))) {
				String enginType = MapUtils.getString(mapvo, "enginType").substring(0);
				mapvo.put("engineType",enginType);
			}else {
				mapvo.put("engineType","");
			}
			mapvo.remove("enginType");
		}
		data.put("stations", maps);
		data.put("total",outServiceStationTotal);
		JSONObject obj = new JSONObject();
		obj.put("status", 0);
		obj.put("msg", "");
		obj.put("data",data);
		//返回客户
		ParameterTool.writeResponse(response, obj.toString());

		return null;
	}

	public JSONArray getStationInfo(List<ServiceStationT> stations) throws JSONException {
		JSONArray ServiceStationJsonArray = new JSONArray();
		for(ServiceStationT station: stations) {
			JSONArray jsonArray = null;
			List<SSRepairT> SSRepairList = null;
			List<EngineTypeT> engineTypeList = null;
			JSONObject content =  new JSONObject();
				
			content.put("id", AESTool.encryptString(station.getId().toString()));
			content.put("stationName", station.getStationname());
			content.put("province", station.getProvince());
			content.put("city", station.getCity());
			content.put("area", station.getArea());
			content.put("address", station.getAddress());
			content.put("distance", station.getDistance());
			content.put("telephone", station.getTelephone());
			content.put("phone", station.getPhone());
			content.put("position", station.getPositionLat()+","+station.getPositionLon());
			content.put("remark", station.getRemark());
			content.put("concact", station.getContact());
			content.put("contact", station.getContact());
			content.put("positionLat", station.getPositionLat());
			content.put("positionLon", station.getPositionLon());

			Map<String, String> dictionariesMap = getDictionary();
			
			/**
			 * 获取服务站的级别SSLevel
			 * 根据服务站id查询服务站维修机型
			 * 根据服务站Id查询服务站图片
			 */
			//获取服务站的级别SSLevel
			SSRepairList = serviceStationDao.findSSRepair(station.getId().toString());
			jsonArray = new JSONArray();
			JSONArray jsonArray1 = new JSONArray();//服务站类型
            List<String> strListVo = new ArrayList<>();
            List<String> strList = Arrays.asList("全职", "保养及外围件维修", "维护保养");
			for(SSRepairT ssRepairT : SSRepairList){
				String SSLevel = dictionariesMap.get("SSLevel"+ssRepairT.getSslevel());
				//去除null和去重
				if( SSLevel!= null && !jsonArray.toString().contains(SSLevel) ){
					jsonArray.put(SSLevel);
				}	
				String SSType = dictionariesMap.get("SSType"+ssRepairT.getSstype());
				//去除null和去重
				if( SSType!= null && !jsonArray1.toString().contains(SSType) ){
                    //jsonArray1.put(SSType);
                    strListVo.add(SSType);
				}
			}
            for (int i = 0; i < strList.size(); i++) {
                String s = strList.get(i);
                if (strListVo.contains(s)) {
                    jsonArray1.put(s);
                }
            }
			content.put("SSLevel", jsonArray);
			content.put("SSType", jsonArray1);
			SSRepairList.clear();
			SSRepairList = null;
			
			//根据服务站id查询服务站维修机型
			engineTypeList = serviceStationDao.findEngineType(station.getId().toString());
			//2.5.0   engineTypeList只能获取出除了dbu以外的机型信息，下面这个集合能够获取出来dbu的机型信息，两个集合去重，展示在服务网点
			List<EngineTypeT> dbuEngineTypeList = serviceStationDao.findEngineTypeByDBU(station.getId().toString());
			if(CollectionUtils.isNotEmpty(dbuEngineTypeList)){
				engineTypeList = Stream.of(engineTypeList, dbuEngineTypeList)
						.flatMap(Collection::stream)
						.distinct()
						.collect(Collectors.toList());
			}


			String engineTypeString = "";
			for(EngineTypeT engineTypeT : engineTypeList){
				engineTypeString += engineTypeT.getTypename()+"、";
			}
			if(engineTypeString.endsWith("、")){
				engineTypeString =  engineTypeString.substring(0, engineTypeString.length()-1);
			}
			content.put("enginType", engineTypeString);
			engineTypeList.clear();
			engineTypeList = null;
			
			//根据服务站Id查询服务站图片 
			int redisCacheTime = Integer.valueOf(propertiesUtils.getPropertiesValue("redisCacheTime"));
			List<ServiceStationImgT> serviceStationImgList = (List<ServiceStationImgT>)redisClientUtils.getObject("serviceStationImg"+station.getId());
			if(serviceStationImgList == null){
				serviceStationImgList = serviceStationDao.findServiceStationImg(station.getId().toString());
				//放入redis中			
				redisClientUtils.setObject("serviceStationImg"+station.getId(), serviceStationImgList, redisCacheTime);
			}
			jsonArray = new JSONArray();
			for(ServiceStationImgT serviceStationImgT : serviceStationImgList){
				jsonArray.put(serviceStationImgT.getImgurl());
			}
			content.put("img", jsonArray);
			serviceStationImgList.clear();
			serviceStationImgList = null;
			//2.10.0全渠道服务网点前台隐藏车辆厂家字段，后台也相应注释掉相应代码，本来查询就慢
//			List<String> companies = serviceStationDao.getCompanyList(station.getId());
//			content.put("companies", companies);

			ServiceStationJsonArray.put(content);
		}
		return ServiceStationJsonArray;
	}
	
	public Map<String, String> getDictionary() {
		Map<String, String> dictionariesMap = (Map<String, String>)redisClientUtils.getObject("dictionariesMap");
		if(dictionariesMap == null){
			int redisCacheTime = Integer.valueOf(propertiesUtils.getPropertiesValue("redisCacheTime"));
			List<DictionariesT> dictionariesList = (List<DictionariesT>)redisClientUtils.getObject("dictionariesList");
			if(dictionariesList == null){
				//放入redis中
				dictionariesList = serviceStationDao.findDictionariesList(null);					
				redisClientUtils.setObject("dictionariesList", dictionariesList, redisCacheTime);
			}
			dictionariesMap = new HashMap<String, String>();
			for(DictionariesT bean : dictionariesList){
				dictionariesMap.put(bean.getDtableName()+bean.getDInt(), bean.getDvalue());
			}
			//放入redis中
			redisClientUtils.setObject("dictionariesMap", dictionariesMap, redisCacheTime);
		}
		return dictionariesMap;
	}
	
}
